import React, { Component } from 'react'

import { Button, Input, message, Upload, Progress, Drawer, Divider, Table, List, Skeleton, Space, Modal } from 'antd';
import { CloudUploadOutlined, UnorderedListOutlined, ExclamationCircleOutlined, ShareAltOutlined, DownloadOutlined, OrderedListOutlined, AppstoreOutlined, RestOutlined } from '@ant-design/icons';

import { getLocalStorage, renderSize, setLocalStorage } from '../../utils/utils'
import { UploadFileURL } from '../../utils/config'
import { GetApi } from '../../api/request'
import './filelistnav.less'


const { Search } = Input;
const { confirm } = Modal;

class FileListNav extends Component {
    state = {
        userid: '',
        account: '',
        visible: false,//上传记录抽屉框显示控制
        uploadData: [],//上传中文件列表
        fileList: [],  //上传完成文件列表
        showModal: false,
        newName: ''
    }
    componentDidMount = () => {
        let fileList = JSON.parse(getLocalStorage('fileList')) || []
        let userInfo = JSON.parse(getLocalStorage('userInfo')) || ''
        this.setState({
            fileList,
            userid: userInfo.id,
            account: userInfo.account
        })
    }
    //上传文件前：文件信息获取函数
    beforeUpload = (file) => {
        let { uploadData } = this.state
        file.key = file.uid
        file.percent = 0
        uploadData.push(file)
        this.setState({
            visible: true,
            uploadData
        })
    }
    //上传文件中：进度监听函数
    handleChange = info => {
        const { event } = info, { uid, status } = info.file
        let { uploadData } = this.state;
        if (event && uploadData.length > 0 && status === "uploading") { // 加判断
            let percent = Math.floor((event.loaded / event.total) * 100)
            uploadData.map(v => uid === v.uid ? v.percent = percent : '')
            this.setState({
                uploadData
            })
        }
        let res = uploadData.some(v => v.percent === 100)
        //上传成功进入完成
        if (status === "done" && res && uploadData.length > 0) {
            let doneIndex = uploadData.findIndex(v => v.percent === 100)
            uploadData.splice(doneIndex, 1)
            this.setState({ uploadData })
            let { data, msg, code } = info.file.response
            if (code === 200) {
                let oneDay = (new Date()).getTime() - 30 * 6000
                let fileList = data.filter((v) => {
                    let fileList = {}
                    if (parseInt(v.upload_date) > oneDay) {
                        fileList.key = v.id
                        fileList.name = v.name
                        fileList.size = v.size
                    }
                    return fileList
                })
                this.setState({ fileList })
                setLocalStorage('fileList', JSON.stringify(fileList))
                setLocalStorage('allFileData', JSON.stringify({ time: Date.now(), data }))
                this.props.setNewData(data)
                if (uploadData.length === 0) {
                    message.destroy();
                    message.success({ content: msg, duration: 4 });
                }
            }

        }
    };
    //上传文件：上传中删除正在上传任务函数
    removeUploadTask = (uid) => {
        let uploadData = this.state.uploadData
        let removeIndex = uploadData.findIndex((v) => v.uid === uid)
        uploadData.splice(removeIndex, 1)
        this.setState({
            uploadData
        })
    }
    //点击删除按钮
    clickDeleteBtn = selectedFileId => {
        let { account } = this.state
        confirm({
            title: '确定要把所选文件放入回收站中吗?',
            icon: <ExclamationCircleOutlined />,
            content: '删除的文件可在10天内通过回收站还原',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                let res = await GetApi('/delete', { account, selectedFileId })
                if (res.data.code === 200) {
                    message.destroy();
                    message.success({ content: res.data.msg, duration: 3 });
                    let { data } = res.data
                    setLocalStorage('allFileData', JSON.stringify({ time: Date.now(), data }))
                    this.props.setNewData(data)
                }
            },
        });
    }
    //点击重命名按钮
    clickReNameBtn = selectedFileId => {
        this.setState({
            showModal: true
        })
    }
    //点击重命名的确定按钮
    clickReNameOkBtn = async (selectedFileId) => {
        let { account, newName } = this.state
        if (newName) {
            let res = await GetApi('/rename', { account, id: selectedFileId[0], newName })
            if (res.data.code === 200) {
                this.setState({ showModal: false })
                message.destroy();
                message.success({ content: res.data.msg, duration: 3 });
                let { data } = res.data
                setLocalStorage('allFileData', JSON.stringify({ time: Date.now(), data }))
                this.props.setNewData(data)
            }
        } else {

        }

    }
    //点击下载按钮
    clickDowmloadBtn = async (id) => {
        console.log(id)
        
        let fileList = this.state.fileList
        let removeIndex = fileList.forEach((v) => v.id === id[0])
        fileList.splice(removeIndex, 1)
        console.log(removeIndex)
    };
    //点击分享按钮
    clickShareBtn = async (selectedFileId) => {
        let { account } = this.state
        confirm({
            title: '确定要分享选中的文件吗?',
            icon: <ExclamationCircleOutlined />,
            content: '分享后全站用户都可进行下载！',
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
                let res = await GetApi('/share', { account, selectedFileId })
                if (res.data.code === 200) {
                    message.destroy();
                    message.success({ content: res.data.msg, duration: 3 });
                    let { data } = res.data
                    setLocalStorage('allFileData', JSON.stringify({ time: Date.now(), data }))
                    this.props.setNewData(data)
                }
            },
        });
    };
    //点击搜索按钮
    clickSearchBtn = async (value, event) => {
        let { data } = this.state
        let newData = data.filter((v) => v.name.search(value) !== -1)
        console.log(newData)
        this.setState({
            data: newData
        })
    };
    render() {
        let selectedFileId = this.props.selectedFileId  //接受父组件传递的选中文件id 数组
        let showBtn = selectedFileId.length > 0 //判断数组长度
        const { account, userid, fileList, visible, uploadData, showModal } = this.state
        const uploadConfig = {
            accept: this.props.accept ? this.props.accept : '',
            action: UploadFileURL,
            data: { account, userid },
            onChange: this.handleChange,
            multiple: true,
            showUploadList: false,
            beforeUpload: this.beforeUpload,
        };
        const doneColumns = [
            {
                dataIndex: 'name',
            },
            {
                dataIndex: 'size',
                render: size => <span>{renderSize(size)}</span>
            },
            {
                dataIndex: 'status',
                width: 80,
                render: () => <span>已完成</span>
            },
        ];

        return (
            <div className="fileListBox">
                <Space className="top-nav">
                    <ul className="myNav">
                        <li><Upload {...uploadConfig}><Button size="large" type="primary" icon={<CloudUploadOutlined />}>上传</Button>
                        </Upload></li>
                        <li><Button size="large" icon={<UnorderedListOutlined />} onClick={() => this.setState({ visible: !visible })}>上传任务</Button></li>
                        <li className={showBtn ? '' : 'btnHide'}><Button size="large" icon={<DownloadOutlined />} onClick={() => this.clickDowmloadBtn(selectedFileId)}>下载</Button></li>
                        <li className={showBtn ? '' : 'btnHide'}><Button size="large" icon={<ShareAltOutlined />} onClick={() => this.clickShareBtn(selectedFileId)}>分享</Button></li>
                        <li className={showBtn ? '' : 'btnHide'}><Button size="large" type="Default" danger icon={<RestOutlined />} onClick={() => this.clickDeleteBtn(selectedFileId)} >删除</Button></li>
                        <li className={showBtn ? '' : 'btnHide'}><Button size="large" disabled={selectedFileId.length > 1 ? true : false} onClick={this.clickReNameBtn}>重命名</Button></li>
                    </ul>
                    <ul className="myNav">
                        <li><Search placeholder="搜索你的文件" size="large" onSearch={this.clickSearchBtn} enterButton /></li>
                        <li><OrderedListOutlined /></li>
                        <li><AppstoreOutlined /></li>
                    </ul>
                </Space>
                <Drawer
                    mask={false}
                    width={500}
                    title="上传记录"
                    placement="right"
                    closable={true}
                    onClose={() => this.setState({ visible: false })}
                    visible={visible}>
                    <Divider plain>上传中({uploadData.length})</Divider>
                    {
                        <List
                            itemLayout="horizontal"
                            dataSource={uploadData}
                            renderItem={item => (
                                <List.Item
                                    actions={[<span>{renderSize(item.size)}</span>, <a href="/#" key="RemoveUploading" onClick={e => { e.preventDefault(); this.removeUploadTask(item.uid) }
                                    }>移除</a>]}>
                                    <Skeleton title={false} loading={item.loading} active>
                                        <List.Item.Meta
                                            title={item.name}
                                            description={<Progress percent={item.percent} />}
                                        />
                                    </Skeleton>
                                </List.Item>
                            )} />
                    }
                    <Divider plain>已完成(最近一天内)</Divider>
                    {
                        <Table showHeader={false} pagination={{ position: ["bottomCenter"] }} columns={doneColumns} dataSource={fileList} />
                    }
                </Drawer>
                <Modal
                    title="重命名"
                    visible={showModal}
                    onOk={() => this.clickReNameOkBtn(selectedFileId)}
                    cancelText="取消"
                    okText="修改"
                    onCancel={() => this.setState({ showModal: false })}>
                    <Input size="large" type="text" placeholder={this.props.fileName} onChange={(e) => this.setState({ newName: e.currentTarget.value })} />
                </Modal>
            </div >
        )
    }
}

export default FileListNav